package com.jfs.qy.config.component;

import cn.hutool.json.JSONUtil;
import com.jfs.qy.chain.component.LoginComponent;
import com.jfs.qy.entity.request.SearchAlarmEventRequest;
import com.jfs.qy.entity.request.SearchAlarmEventRequestData;
import com.jfs.qy.entity.response.SearchAlarmEventResponse;
import com.jfs.qy.entity.response.SearchAlarmEventResponseData;
import com.jfs.qy.enums.TaskKeyEnum;
import com.jfs.qy.service.AlarmEventService;
import com.jfs.qy.service.LogoutService;
import com.jfs.qy.session.NvrSessionStorage;
import com.jfs.qy.strategy.AlarmEventProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;

/**
 * @Description 查询告警任务
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/4
 */
@Slf4j
public class AlarmTask implements Task {
    private final AlarmEventService alarmEventService;
    private final LogoutService logoutService;
    private final LoginComponent loginComponent;
    private final List<AlarmEventProcessStrategy> alarmEventProcessStrategyList;

    public AlarmTask(AlarmEventService alarmEventService,  List<AlarmEventProcessStrategy> alarmEventProcessStrategyList,LogoutService logoutService,LoginComponent loginComponent) {
        this.alarmEventService = alarmEventService;
        this.alarmEventProcessStrategyList = alarmEventProcessStrategyList;
        this.logoutService=logoutService;
        this.loginComponent=loginComponent;
    }

    @Override
    public String getKey() {
        return TaskKeyEnum.ALARM_KEY.getKey();
    }

    @Override
    public void run() {
      try {
          //创建请求参数对象
          SearchAlarmEventRequest searchAlarmEventRequest = new SearchAlarmEventRequest();
          SearchAlarmEventRequestData.Builder intelligence = new SearchAlarmEventRequestData.Builder()
                  .aiMetadata(true)
                  .needBackgroundImg(true)
                  .intelligence(true);
          if (Objects.nonNull(NvrSessionStorage.readerId) &&
                  Objects.nonNull(NvrSessionStorage.lapNumber) &&
                  Objects.nonNull(NvrSessionStorage.sequence)){
              intelligence.lapNumber(NvrSessionStorage.lapNumber)
                      .readerId(NvrSessionStorage.readerId)
                      .sequence(NvrSessionStorage.sequence);
          }
          SearchAlarmEventRequestData request = intelligence.build();
          searchAlarmEventRequest.setData(request);
          if (log.isDebugEnabled()){
              log.debug("发起查询告警请求，请求参数readerId:{},lapNumber:{},sequence:{}",NvrSessionStorage.readerId,NvrSessionStorage.lapNumber,NvrSessionStorage.sequence);
          }//发送请求
          ResponseEntity<SearchAlarmEventResponse> searchAlarmEventResponseResponseEntity = alarmEventService.searchAlarmEvent(searchAlarmEventRequest);
          if (Objects.nonNull(searchAlarmEventResponseResponseEntity)&&HttpStatus.OK.equals(searchAlarmEventResponseResponseEntity.getStatusCode())){
              SearchAlarmEventResponseData data = Objects.requireNonNull(searchAlarmEventResponseResponseEntity.getBody()).getData();
              if (log.isDebugEnabled()){
                  log.debug("查询到告警所有详情:{}", JSONUtil.toJsonStr(data));
              }
              if (Objects.nonNull(data)&&Objects.nonNull(data.getLapNumber())&&Objects.nonNull(data.getSequence())&&Objects.nonNull(data.getReaderId())) {
                  //设置下一次请求查询事件的链路信息
                  NvrSessionStorage.lapNumber = data.getLapNumber();
                  NvrSessionStorage.sequence = data.getSequence();
                  NvrSessionStorage.readerId = data.getReaderId();
                  //处理告警
                  for (AlarmEventProcessStrategy alarmEventProcessStrategy:alarmEventProcessStrategyList
                  ) {
                      if (alarmEventProcessStrategy.isMatch(data.getAlarmList())){
                          alarmEventProcessStrategy.doProcessAlarmEvent(data.getAlarmList());
                      }
                  }
              }
          }
      }catch (Exception e){
          //注销
          logoutService.logout();
          //再次登录
          try {
              loginComponent.login();
          } catch (URISyntaxException ex) {
              throw new RuntimeException(ex);
          } catch (NoSuchAlgorithmException ex) {
              throw new RuntimeException(ex);
          } catch (KeyStoreException ex) {
              throw new RuntimeException(ex);
          } catch (KeyManagementException ex) {
              throw new RuntimeException(ex);
          }
          e.printStackTrace();
      }

    }
}
